<template>
	<view class="chat-container">
		<view class="cu-chat">
			<scroll-view
				scroll-y="true"
				@click="resetData"
				:scroll-into-view="scrollToView"
				:scroll-with-animation="false"
				:style="{ height: scrollViewHeight }"
			>
				<template v-for="(item, index) in messageList">
					<view
						class="cu-item self"
						v-if="item.userId === userInfo.id"
						:id="'message' + item.id"
						:key="item.id"
					>
						<view class="main">
							<view class="content bg-green shadow">
								<text>{{ item.content }}</text>
							</view>
						</view>
						<view class="cu-avatar radius"><image :src="userInfo.avatar" mode="aspectFill"></image></view>
						<!-- <view class="date">2018年3月23日 13:23</view> -->
					</view>
					<view class="cu-item" v-else :id="'message' + item.id" :key="item.id">
						<view class="cu-avatar radius"><image :src="friend.avatar" mode="aspectFill"></image></view>
						<!-- <view class="date">2018年3月23日 13:23</view> -->
						<view class="main">
							<view class="content shadow">
								<text>{{ item.content }}</text>
							</view>
						</view>
					</view>
				</template>
			</scroll-view>
		</view>
		<!-- 底部输入框 -->
		<view class="cu-bar foot input" :style="{ bottom: `${keyboardHeight}rpx` }">
			<view class="action"><text class="cuIcon-sound text-grey" style="font-size: 58rpx;"></text></view>
			<view class="textarea-box">
				<textarea
					v-model="content"
					auto-height
					:fixed="true"
					:maxlength="300"
					:cursor-spacing="15"
					:confirm-hold="true"
					:show-confirm-bar="false"
					:adjust-position="false"
					:hold-keyboard="true"
					@linechange="handleLineChange"
				></textarea>
			</view>
			<view class="action"><text class="cuIcon-emojifill text-grey" style="font-size: 58rpx;"></text></view>
			<button class="cu-btn bg-green shadow" @click.stop="sendMessage">发送</button>
		</view>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import socketManager from '@/utils/websocket.js';
import { unitConvert } from '@/utils/index.js';

export default {
	data() {
		return {
			keyboardHeight: 0, // 键盘高度
			textareaHeight: 0, // 文本框高度
			scrollToView: '', // 滚动到元素的ID
			content: '' // 聊天内容
		};
	},
	computed: {
		...mapState(['userInfo', 'activeRoom', 'friendGather']),
		// 获取聊天列表
		messageList() {
			const friend = this.friendGather.find(item => item.friendId === this.activeRoom);
			if (friend && friend.messages) {
				this.showLastMessage();
				return friend.messages;
			}
			return [];
		},
		// 获取好友信息
		friend() {
			const friend = this.friendGather.find(item => item.friendId === this.activeRoom);
			if (friend) {
				return { nickname: friend.nickname, avatar: friend.avatar };
			}
			return {};
		},
		// 滚动视图高度
		scrollViewHeight() {
			this.scrollToView = '';
			this.showLastMessage();
			return `calc(100vh - ${this.textareaHeight + this.keyboardHeight}rpx)`;
		}
	},
	onLoad() {
		// 进来时清除当前好友未读信息
		this.$store.commit('LOSE_READ_GATHER', { userId: this.activeRoom, isSet: false });
		// 获取键盘高度
		uni.onKeyboardHeightChange(res => {
			this.keyboardHeight = unitConvert(res.height);
		});
	},
	onUnload() {
		// 离开时把当前好友设置为空
		this.$store.commit('SET_ACTIVE_ROOM', '');
	},
	methods: {
		// 发送消息
		sendMessage() {
			const { content, activeRoom, userInfo } = this;
			if (this.content.trim() !== '') {
				const socket = socketManager.getSocket();
				socket.emit('friendMessage', { userId: userInfo.id, friendId: activeRoom, content });
				this.content = '';
			}
		},
		// 重置数据
		resetData() {
			this.keyboardHeight = 0;
			uni.hideKeyboard();
		},
		// 获取发送框高度
		handleLineChange() {
			this.$nextTick(() => {
				let query = uni.createSelectorQuery();
				query.select('.cu-bar').boundingClientRect();
				query.exec(res => {
					this.textareaHeight = unitConvert(res[0].height);
				});
			});
		},
		// 滚动到最后一条消息
		showLastMessage() {
			this.$nextTick(() => {
				const index = this.messageList.length - 1;
				if (this.messageList[index] && this.messageList[index].id) {
					this.scrollToView = 'message' + this.messageList[index].id;
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.cu-avatar image {
	width: 100%;
	height: 100%;
}

.cu-bar {
	padding: 20rpx 0;
	padding-right: 20rpx;
	align-items: flex-end;
	background-color: #f5f5f5 !important;
	.textarea-box {
		width: 80%;
		padding: 16rpx 0;
		border-radius: 6rpx;
		background-color: #fff;
		textarea {
			width: 100%;
			font-size: 16px;
			padding-left: 10rpx;
			background-color: #fff;
		}
	}
	.cu-btn {
		width: 132rpx;
		margin-left: 10px;
	}
}
</style>
